<?php
declare (strict_types=1);

namespace app\store\model\user;

use app\common\model\user\Application as Model;
use app\store\model\User;
use think\db\exception\DbException;
use think\Paginator;
use ZipArchive;

class Application extends Model
{
    /**
     * 获取用户列表
     * @param array $param
     * @return Paginator
     * @throws DbException
     */
    public function getList($param = [])
    {
        // 查询模型
        $query = $this->getNewQuery();
        // 查询参数
        $filter = $this->getQueryFilter($param);

        if (!empty($param['export']) && $param['export'] == 1) {
            $list = $query
                ->with(['channel', 'user', 'job', 'subject_level'])
                ->where($filter)
                ->where('is_delete', '=', '0')
                ->order(['create_time' => 'desc'])
                ->select();
            $this->baseExport('导出Excel' . date('YmdHis'), $list);
        }

        // 查询列表记录
        $list = $query
            ->with(['channel', 'user', 'face_file', 'comsign_file', 'examsign_file', 'job', 'subject_level'])
            ->where($filter)
            ->where('is_delete', '=', '0')
            ->order(['create_time' => 'desc'])
            ->paginate(15);
        return $list;
    }

    public function getQueryFilter($param)
    {
        $params = $this->setQueryDefaultValue($param, [
            'full_name' => '',
            'idnumber' => '',
            'channel_id' => '',
            'application_id' => [],
            'status' => -1,
        ]);

        $filter = [];
        if (!empty($params['full_name']) && !empty($params['idnumber'])) {
            $user_id = (new User())->where([
                ["full_name", "like", "%{$params['full_name']}%"],
                ["idnumber", "like", "%{$params['idnumber']}%"],
                ["is_delete", "=", 0],
            ])->column('user_id');
            $filter[] = ["user_id", "in", $user_id];
        } elseif (!empty($params['full_name'])) {
            $user_id = (new User())->where([
                ["full_name", "like", "%{$params['full_name']}%"],
                ["is_delete", "=", 0],
            ])->column('user_id');
            $filter[] = ["user_id", "in", $user_id];
        } elseif (!empty($params['idnumber'])) {
            $user_id = (new User())->where([
                ["idnumber", "like", "%{$params['idnumber']}%"],
                ["is_delete", "=", 0],
            ])->column('user_id');
            $filter[] = ["user_id", "in", $user_id];
        }


        !empty($params['application_id']) && $filter[] = ["application_id", "in", $params['application_id']];
        !empty($params['channel_id']) && $filter[] = ["channel_id", "in", $params['channel_id']];
        $params['status'] > -1 && $filter[] = ["status", "=", $params['status']];

        if (!empty($params['create_time'])) {
            $times = between_time($params['create_time']);
            $filter[] = ['create_time', '>=', $times['start_time']];
            $filter[] = ['create_time', '<', $times['end_time'] + 86400];
        }
        return $filter;
    }

    public function baseExport($excelFileName, $list)
    {
        $excelTableHeader = [
            '学员姓名',
            '身份证号',
            '报考工种',
            '工种等级',
            '累计学时（分钟）',
            '考试分数',
            '试卷查看地址',
        ];
        $data = [];
        foreach ($list as $k => $v) {
            $data[$k][] = $v->user ? $v->user->full_name : '';
            $data[$k][] = $v->user ? $v->user->idnumber : '';
            $data[$k][] = $v->subject ? $v->subject->subject_name : '';
            $data[$k][] = $v->subject_level ? $v->subject_level->level_name : '';
            $data[$k][] = $v->accumulate_learn;
            $data[$k][] = $v->exam_score;
            $data[$k][] = $v->last_paper ? base_url() . 'index.php?s=/api/index/paperpreview&paper_id=' . $v->last_paper->paper_id : '';
        }
        excelExport($excelFileName, $excelTableHeader, $data);
    }


    /**
     * 增加记录
     * @param array $data
     * @return bool
     */
    public function add($data)
    {
        $data['store_id'] = self::$storeId;
        return $this->save($data);
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool
     */
    public function edit(array $data)
    {
        return $this->save($data);
    }

    public function batchEdit($ids, $data)
    {
        return $this->where('application_id', 'in', $ids)->save($data);
    }


    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }


    public function exportAvatar($param = [])
    {
        // 查询模型
        $query = $this->getNewQuery();
        // 查询参数
        $filter = $this->getQueryFilter($param);

        $list = $query
            ->with(['face_file'])
            ->where($filter)
            ->where('is_delete', '=', '0')
            ->order(['create_time' => 'desc'])
            ->select();
        if (!count($list)) {
            $this->error = '未查询到数据!';
            return false;
        }


        $filename = 'zip/Avatar' . date('YmdHis') . ".zip";
        $uploadPath = ROOT_PATH() . 'public/uploads/' . $filename;
        $zip = new ZipArchive();
        $zip->open($uploadPath, ZipArchive::CREATE);
        foreach ($list as $v) {
            if (!$v->face_file) {
                continue;
            }
            $file = web_path() . 'uploads/' . $v->face_file->file_path;
            // $file = str_replace('/', '\\', $file);
            if (file_exists($file)) {
                $new_filename = $v->user ? $v->user->idnumber : '';
                $fname = pathinfo($file, PATHINFO_FILENAME);
                $nname = str_replace($fname, $new_filename, $file);
                copy($file, $nname);
                $zip->addFile($nname, basename($nname));
            }
        }
        $zip->close();
        return ["url" => uploads_url() . $filename];
    }
}
